//
//  MusicManagerView.swift
//  Reader
//
//  Created by mn on 2024/9/26.
//

import UIKit
import AVFoundation
import SnapKit

let sw = UIScreen.main.bounds.size.width
let sh = UIScreen.main.bounds.size.height

class MusicManagerView: UIView{
    static let shared = MusicManagerView(frame: .zero)
    
    var changed:((File) -> Void)? = nil
    
    private override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = CGRect(x: 0, y: sh - 50 - TabBarHeight, width: sw, height: 50)
        let blurEffect = UIBlurEffect(style: .light) // 其他风格，如 .dark、.extraLight 等
        let visualEffectView = UIVisualEffectView(effect: blurEffect)
        visualEffectView.frame = self.bounds // 设置其大小与你的视图相同
        visualEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // 使其能够响应大小变化
        self.addSubview(visualEffectView)
        durtionLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        controlBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.width.height.equalTo(40)
            make.centerY.equalToSuperview()
        }
        progressView.snp.makeConstraints { make in
            make.right.equalTo(durtionLabel.snp.left).offset(-10)
            make.centerY.equalToSuperview()
            make.left.equalTo(controlBtn.snp.right).offset(10)
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var files = [File]()
    var currentFile: File?{
        didSet{
            guard let currentFile  else { return }
            playAudio(url: currentFile.path)
            changed?(currentFile)
        }
    }
    lazy var durtionLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.font = UIFont.systemFont(ofSize: 15)
        label.textAlignment = .right
        self.addSubview(label)
        label.text = "00:00 / 00:00"
        return label
    }()
    
    lazy var progressView = {
        let progressView = UIProgressView(progressViewStyle: .default)
        progressView.frame = CGRect(x: 50, y: 23, width: 100, height: 4)
        progressView.progress = 0.0
        progressView.progressTintColor = UIColor.blue
        progressView.trackTintColor = UIColor.lightGray
        addSubview(progressView)
        return progressView
    }()
    lazy var controlBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "play"), for: .normal)
        btn.setImage(UIImage(named: "stop"), for: .selected)
        addSubview(btn)
        btn.addTarget(self, action: #selector(controlBtnAction), for: .touchUpInside)
        return btn
    }()

    @objc func controlBtnAction(_ sender:UIButton){
        if sender.isSelected{
            avPlayer?.pause()
        }else{
            avPlayer?.play()
        }

        sender.isSelected = !sender.isSelected
    }
    
    var avPlayer: AVPlayer?
    func playAudio(url: URL) {
        avPlayer = AVPlayer(url: url)
        avPlayer?.addPeriodicTimeObserver(forInterval:CMTime(value: 1, timescale: 1), queue: nil) {
            [weak self] (time) in
            guard let durtion =  self?.currentFile?.durtion else { return }
            let currentTime = CMTimeGetSeconds(time)
            DispatchQueue.main.async{
                self?.progressView.progress = Float(currentTime / durtion)
                self?.durtionLabel.text = "\(currentTime.secondsToHMS()) / \(self?.currentFile?.durtionString ?? "-:-")"
            }
        }
    }
}
